package com.java.springboot.Realm;

import com.java.springboot.model.User;
import com.java.springboot.service.UserserviceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserserviceImpl userservice;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }
    /**
     * 认证
     * @param Token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken Token) throws AuthenticationException {
        String username = Token.getPrincipal().toString();
        User user = userservice.UserByUserName(username);
        if (user != null){
            SimpleAuthenticationInfo Info = new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
            System.out.println("认证成功");
            return Info;
        }else {
            return null;
        }
    }

    /**
     * 授权
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        User user = (User) principal.getPrimaryPrincipal();
        User role = userservice.selectrolename(user.getId());
        String rolename = role.getRole().getRolename();
        System.out.println("用户角色"+rolename);
        String Permission = "";
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(rolename);
        info.addStringPermission(Permission);
        System.out.println("授权成功");
        return info;
    }


}
